const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    trainDate: '',
    trainTypeList: [{
        name: '力量训练',
        imageSrc: '',
        description: '通过多组负重训练达到改善肌肉,耐力和形状的运动方式.',
        selected: false
      },
      {
        name: '有氧运动',
        imageSrc: '',
        description: '指人体在氧气充分供给的情况下进行的锻炼.如:慢跑,骑车等.',
        selected: false
      },
      {
        name: '核心训练',
        imageSrc: '',
        description: '核心训练位躯干部的审查肌肉群的耐力训练,能起到稳定性的作用.',
        selected: false
      },
      {
        name: '体能训练',
        imageSrc: '',
        description: '通过力量,速度,耐力,协调,灵敏等运动素质表现出的运动能力.',
        selected: false
      },
      {
        name: '康复训练',
        imageSrc: '',
        description: '采用适量,定向,有针对性的机体运动来帮助身体恢复到正常状态.',
        selected: false
      },
      {
        name: '柔软性改善',
        imageSrc: '',
        description: '指人体关节活动幅度和关节韧带,肌腱,肌肉,皮肤和其他组织的伸展能力,即关节和关节系统的活动范围.',
        selected: false
      },
      {
        name: '其他类型',
        imageSrc: '',
        description: '不属于以上选项的训练类型',
        selected: false
      }
    ]
  },
  onLoad: function(options) {
    const trainId = wx.getStorageSync("trainId");
    const trainTypesJson = wx.getStorageSync("trainTypes");
    const selectTrainTypes = JSON.parse(trainTypesJson) || [];
    const trainTypeList = this.data.trainTypeList;
    trainTypeList.forEach(function(item) {
      if (selectTrainTypes.indexOf(item.name) >= 0) {
        item.selected = true;
      }
    });
    this.setData({
      trainTypeList: trainTypeList
    });
  },
  changeSelect: function(e) {
    const index = e.currentTarget.dataset.index;
    const trainTypeList = this.data.trainTypeList;
    trainTypeList[index].selected = !trainTypeList[index].selected;
    this.setData({
      trainTypeList: trainTypeList
    });
  },
  
  saveType: function() {
    const selectedTypeList = [];
    const trainTypeList = this.data.trainTypeList;
    trainTypeList.forEach(function(item) {
      if (item.selected) {
        selectedTypeList.push(item.name);
      }
    });
    const trainTypes = selectedTypeList.join(',');
    const url = app.globalData.url;
    const openId = app.globalData.openId;
    const trainDate = this.data.trainDate;
    wx.request({
      url: url + '/train/saveTypes',
      data: {
        openId: openId,
        trainDate: trainDate,
        trainTypes: trainTypes
      },
      method: 'POST',
      success: function (response) {
        if (response.data.success) {
          //保存 
          wx.navigateBack({
            delta: 1
          });
          wx.showToast({
            title: '保存成功',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: '保存失败:' + response.data.message,
            icon: 'none'
          })
        }
      }
    })
  }
})